from kivy.app import App
from kivy.lang import Builder
from kivy.effects.opacityscroll import OpacityScrollEffect
from kivy.metrics import sp
from kivy.properties import BooleanProperty

Builder.load_file('goblinoid/feed/kv/refreshscrolleffect.kv')


class RefreshScrollEffect(OpacityScrollEffect):

    user_did_refresh = BooleanProperty(False)

    def on_overscroll(self, instance, pos):
        if not self.user_did_refresh and (pos * -1) > sp(5):
            App.get_running_app().dispatch_event('on_pull_to_refresh', (pos*-1) / sp(100))
        if (-1 * pos) > sp(100):
            self.user_did_refresh = True
        elif pos > sp(1):
            self.reset(0)
            self.user_did_refresh = False
        elif pos == 0:
            self.user_did_refresh = False

    def on_user_did_refresh(self, instance, call_refresh):
        if call_refresh and self.target_widget is not None:
            print ('refresh did get called by overscroll')
            self.target_widget.parent.request_feed_refresh()
